package com.digital.community;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class TBTaskAttachment extends Activity {
	// protected static final int TAKE_PHOTO_ID = 0;
	protected static final int TAKE_PHOTO_0 = 0;
	protected static final int TAKE_PHOTO_1 = 1;
	protected static final int TAKE_PHOTO_2 = 2;
	protected ImageView imgAtt1, imgAtt2,imgAtt3, voiceAtt3;//四个附件，两个图片一个音频
	protected Button  btnAtt3, btnStop;
	protected Button imgBtnAtt1,imgBtnAtt2,imgBtnAtt3,btnBack;
	protected TextView tv;
	private MediaRecorder recorder;
	// public MyConstants myConstants;
	public String path1, path2;
	private File tempFile, SDPathDir;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.attachement);

		imgBtnAtt1 = (Button) findViewById(R.id.btnAtt1);
		imgBtnAtt2 = (Button) findViewById(R.id.btnAtt2);
		imgBtnAtt3 = (Button) findViewById(R.id.btnAtt4);
		imgAtt1 = (ImageView) findViewById(R.id.imgAtt1);
		imgAtt2 = (ImageView) findViewById(R.id.imgAtt2);
		imgAtt3 = (ImageView) findViewById(R.id.imgAtt3);
		voiceAtt3 = (ImageView) findViewById(R.id.voiceAtt3);
		btnAtt3 = (Button) findViewById(R.id.btnAtt3);
		btnStop = (Button) findViewById(R.id.btnStop);
		
		tv = (TextView) findViewById(R.id.recordStatus);
		btnBack=(Button)findViewById(R.id.btnReturnBack);
		/*
		 * 录音程序
		 */
		btnAtt3.setEnabled(true);
	btnStop.setEnabled(false);
	//	btnOK.setEnabled(false);
		buttonListener();

	}

	private void buttonListener() {
		// TODO Auto-generated method stub

		btnBack.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i=new Intent();
				i.setClass(TBTaskAttachment.this, TBTaskActivity.class);
				startActivity(i);
			}
			
		});
		
		/*
		 * 点击拍照
		 */
		imgBtnAtt1.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(i, TAKE_PHOTO_0);
			}

		});

		imgBtnAtt2.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(i, TAKE_PHOTO_1);
			}

		});
		imgBtnAtt3.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
				startActivityForResult(i, TAKE_PHOTO_2);
			}

		});
		// 开始录音
		btnAtt3.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				initRecorder();
				startRecorder();
				tv.setText("正在录音……");
				btnAtt3.setEnabled(false);
				btnStop.setEnabled(true);
			//	btnOK.setEnabled(true);
			}
		});
		// 停止录音
		btnStop.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				stopRecorder();
				tv.setText("录音已停止");
				btnAtt3.setEnabled(true);
				btnStop.setEnabled(false);
			//	btnOK.setEnabled(true);
			}
		});
		// Ok按钮点击
		

	}

	protected void startRecorder() {
		// TODO Auto-generated method stub
		try {
			recorder.prepare();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		recorder.start();
	}

	protected void initRecorder() {
		// TODO Auto-generated method stub
		recorder = new MediaRecorder();
		/* 设置音频源 */
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		/* 设置输出格式 */
		recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		/* 设置音频编码器 */
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		// try {
		/* 创建一个临时文件，用来存放录音 */
		// tempFile = File.createTempFile("tempFile", ".amr", SDPathDir);
		// File SDPathDir = Environment.getExternalStorageDirectory();
		// String path = SDPathDir.getParent() + SDPathDir.getName();
		String recordFileName = createFileName();
		String recordName = "/mnt/sdcard/" + recordFileName + ".amr";
		File aFile = new File(recordName);
		// } catch (IOException e) {
		// TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		/* 设置录音文件 */
		recorder.setOutputFile(aFile.getAbsolutePath());
		MyConstants.recordePath = aFile.getAbsolutePath();
	}

	protected void stopRecorder() {
		// TODO Auto-generated method stub
		if (recorder != null) {
			recorder.stop();
			recorder.release();// 释放资源
			recorder = null;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (TAKE_PHOTO_0 == requestCode) {
			if (resultCode != RESULT_OK)
				return;
			Bundle extras = data.getExtras();
			try {
				Bitmap photoCaptured = (Bitmap) extras.get("data");
				/*
				 * ImageView img = new ImageView(this);
				 * img.setImageBitmap(photoCaptured); setContentView(img);
				 */
				imgAtt1.setImageBitmap(photoCaptured);
				// store to sd card
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				photoCaptured.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				byte[] photoBytes = baos.toByteArray();
				String fileName = createFileName();// 创建文件名

				String photoName = "/mnt/sdcard/" + fileName + ".jpg";
				File aFile = new File(photoName);
				String photoPath = aFile.getAbsolutePath();
				MyConstants.imgAtt1Path = photoPath;
				// path1=photoPath;
				// MyConstants myconstants=(MyConstants)getApplicationContext();
				// myconstants.setImgAtt1Path(photoPath);
				// myConstants.imgAtt1Path=photoPath;
//				Toast.makeText(TBTaskAttachment.this, MyConstants.imgAtt1Path,
//						Toast.LENGTH_SHORT).show();

				boolean b;
				if (aFile.exists())
					b = aFile.delete();
				// f.mkdirs();
				aFile.createNewFile(); // need add permission to manifest

				FileOutputStream fos = new FileOutputStream(aFile);
				fos.write(photoBytes);
				fos.close();
				Log.d("info", "onPictureTaken - wrote bytes: "
						+ photoBytes.length);
				Uri capturedImage = Uri
						.parse(android.provider.MediaStore.Images.Media
								.insertImage(getContentResolver(),
										aFile.getAbsolutePath(), null, null));
				Log.i("camera", "Selected image: " + capturedImage.toString());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		} else if (TAKE_PHOTO_1 == requestCode) {
			if (resultCode != RESULT_OK)
				return;
			Bundle extras = data.getExtras();
			try {
				Bitmap photoCaptured = (Bitmap) extras.get("data");
				/*
				 * ImageView img = new ImageView(this);
				 * img.setImageBitmap(photoCaptured); setContentView(img);
				 */
				imgAtt2.setImageBitmap(photoCaptured);
				// store to sd card
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				photoCaptured.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				byte[] photoBytes = baos.toByteArray();
				String fileName = createFileName();
				String photoName = "/mnt/sdcard/" + fileName + ".jpg";
				File aFile = new File(photoName);
				String photoPath = aFile.getAbsolutePath();
				// myConstants.imgAtt1Path1=photoPath;
				// path2=photoPath;
				MyConstants.imgAtt1Path1 = photoPath;
				boolean b;
				if (aFile.exists())
					b = aFile.delete();
				// f.mkdirs();
				aFile.createNewFile(); // need add permission to manifest

				FileOutputStream fos = new FileOutputStream(aFile);
				fos.write(photoBytes);
				fos.close();
				Log.d("info", "onPictureTaken - wrote bytes: "
						+ photoBytes.length);
				Uri capturedImage = Uri
						.parse(android.provider.MediaStore.Images.Media
								.insertImage(getContentResolver(),
										aFile.getAbsolutePath(), null, null));
				Log.i("camera", "Selected image: " + capturedImage.toString());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		} else if (TAKE_PHOTO_2 == requestCode) {
			if (resultCode != RESULT_OK)
				return;
			Bundle extras = data.getExtras();
			try {
				Bitmap photoCaptured = (Bitmap) extras.get("data");
				/*
				 * ImageView img = new ImageView(this);
				 * img.setImageBitmap(photoCaptured); setContentView(img);
				 */
				imgAtt3.setImageBitmap(photoCaptured);
				// store to sd card
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				photoCaptured.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				byte[] photoBytes = baos.toByteArray();
				String fileName = createFileName();
				String photoName = "/mnt/sdcard/" + fileName + ".jpg";
				File aFile = new File(photoName);
				String photoPath = aFile.getAbsolutePath();
				// myConstants.imgAtt1Path1=photoPath;
				// path2=photoPath;
				MyConstants.imgAtt1Path2 = photoPath;
				boolean b;
				if (aFile.exists())
					b = aFile.delete();
				// f.mkdirs();
				aFile.createNewFile(); // need add permission to manifest

				FileOutputStream fos = new FileOutputStream(aFile);
				fos.write(photoBytes);
				fos.close();
				Log.d("info", "onPictureTaken - wrote bytes: "
						+ photoBytes.length);
				Uri capturedImage = Uri
						.parse(android.provider.MediaStore.Images.Media
								.insertImage(getContentResolver(),
										aFile.getAbsolutePath(), null, null));
				Log.i("camera", "Selected image: " + capturedImage.toString());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	/*
	 * 以时间戳为基准，创建文件名
	 */
	private String createFileName() {
		// TODO Auto-generated method stub
		Calendar ca = Calendar.getInstance();
		int year = ca.get(Calendar.YEAR);// 获取年份
		int month = ca.get(Calendar.MONTH);// 获取月份
		int day = ca.get(Calendar.DATE);// 获取日
		int minute = ca.get(Calendar.MINUTE);// 分
		int hour = ca.get(Calendar.HOUR);// 小时
		int second = ca.get(Calendar.SECOND);// 秒
		String fileName = String.valueOf(year) + String.valueOf(month)
				+ String.valueOf(day) + String.valueOf(hour)
				+ String.valueOf(minute) + String.valueOf(second);
		return fileName;
	}
}
